package com.agenda.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;
import com.agenda.concorrencia.Semaforo;

public abstract class DefaultController<MODEL> {

	private List<MODEL> data = new ArrayList<MODEL>();

	private String nomeArquivo;

	protected Semaforo semaforo;

	protected DefaultController(String nomeArquivo) {
		this.nomeArquivo = nomeArquivo;
		semaforo = new Semaforo();
	}

	public void gravar(MODEL model) {
		try {
			semaforo.DOWN();

			gravarSemSemaforo(model);
		} finally {
			semaforo.UP();
		}
	}

	protected void preGravacao(MODEL model) {

	}

	public List<MODEL> getRegistros() {
		try {
			semaforo.DOWN();
			return getRegistrosSemSemaforo();
		} finally {
			semaforo.UP();
		}
	}

	protected List<MODEL> getRegistrosSemSemaforo() {
		carregar();
		return data;
	}

	private void gravar() {
		try {
			FileOutputStream fileOutput = new FileOutputStream(new File(nomeArquivo));
			ObjectOutputStream objouPut = new ObjectOutputStream(fileOutput);

			objouPut.writeObject(data);

			objouPut.flush();
			fileOutput.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void carregar() {
		try {
			File arquivoDeDados = new File(nomeArquivo);
			if (arquivoDeDados.exists()) {
				FileInputStream fileOutput = new FileInputStream(arquivoDeDados);
				ObjectInputStream objouPut = new ObjectInputStream(fileOutput);

				data = (List<MODEL>) objouPut.readObject();

				fileOutput.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	protected void gravarSemSemaforo(MODEL model) {
		preGravacao(model);

		int index = data.indexOf(model);
		if (index < 0)
			data.add(model);
		else
			data.set(index, model);

		gravar();
	}
}
